package com.hzkq.widgets.chart.simple;

import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.Paint.Style;
import android.graphics.Path;
import android.graphics.RectF;
import android.graphics.Shader;
import android.os.Bundle;
import android.widget.Button;

import com.hzkq.widgets.R;
import com.keqiang.chart.impl.axis.Label;
import com.keqiang.chart.impl.axis.XAxis;
import com.keqiang.chart.impl.axis.YAxis;
import com.keqiang.chart.impl.axis.impl.line.AddedLine;
import com.keqiang.chart.impl.axis.impl.line.Gravity;
import com.keqiang.chart.impl.axis.impl.line.LineChart;
import com.keqiang.chart.impl.axis.impl.line.LineChartHighLightRender;
import com.keqiang.chart.impl.axis.impl.line.LineChartView;
import com.keqiang.chart.impl.axis.impl.line.LineData;
import com.keqiang.chart.impl.axis.impl.line.LineEntity;
import com.keqiang.chart.impl.axis.impl.line.LineStyle;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import me.zhouzhuo810.magpiex.ui.act.BaseActivity;
import me.zhouzhuo810.magpiex.ui.widget.TitleBar;
import me.zhouzhuo810.magpiex.utils.SimpleUtil;

/**
 * @author Created by 汪高皖 on 2020/1/4 10:26
 */
public class LineChartActivity extends BaseActivity {
    
    private TitleBar mTitleBar;
    private LineChart mLineChart;
    private LineChart mLineChart2;
    private Button mBtRefresh;
    private LinearGradient mGradient;
    
    @Override
    public int getLayoutId() {
        return R.layout.activity_simple_line_chart;
    }
    
    @Override
    public boolean shouldSupportMultiLanguage() {
        return false;
    }
    
    @Override
    public void initView(@Nullable Bundle savedInstanceState) {
        mTitleBar = findViewById(R.id.title_bar);
        LineChartView lineChartView = findViewById(R.id.line_chart);
        mLineChart = lineChartView.getChart();
        LineChartView lineChartView2 = findViewById(R.id.line_chart2);
        mLineChart2 = lineChartView2.getChart();
        mBtRefresh = findViewById(R.id.bt_refresh);
        
        initLineChart();
        initLineChart2();
    }
    
    @Override
    public void initData() {
        fillLineChart1Data();
        fillLineChart2Data();
    }
    
    @Override
    public void initEvent() {
        mTitleBar.getLlLeft().setOnClickListener(v -> closeAct());
        
        mBtRefresh.setOnClickListener(v -> fillLineChart2Data());
    }
    
    Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    Path mPath = new Path();
    
    private void initLineChart() {
        XAxis xAxis = mLineChart.getXAxis();
        xAxis.setDrawGridLine(true);
        xAxis.setGridUseEndPadding(true);
        xAxis.setLabelAlign(Align.CENTER);
        xAxis.setLabelOverAlign(Align.LEFT);
        xAxis.setLabelCount(6);
        xAxis.setLabelMaxLines(2);
        xAxis.setLabelOffsetAxis(SimpleUtil.getScaledValue(10));
        xAxis.setEndPadding(SimpleUtil.getScaledValue(30));
        
        YAxis yAxis = mLineChart.getYAxis();
        yAxis.setDrawGridLine(true);
        yAxis.setGridUseEndPadding(true);
        yAxis.setLabelAlign(Align.RIGHT);
        yAxis.setLabelMaxLines(2);
        yAxis.setLabelOffsetAxis(SimpleUtil.getScaledValue(10));
        yAxis.setEndPadding(SimpleUtil.getScaledValue(30));
        yAxis.setLabelMaxWidth(SimpleUtil.getScaledValue(100f));
        yAxis.setLabelCount(6);
        yAxis.setLabelMinWidth(SimpleUtil.getScaledValue(60));
        yAxis.setMin(0);
        yAxis.setMax(100);
        
        mLineChart.setHighLightRender(new LineChartHighLightRender(mLineChart, Color.GREEN, 4f) {
            @Override
            public CharSequence getText(@NonNull LineEntity lineEntity) {
                return lineEntity.getValue() + "";
            }
            
            @Override
            public float getTextSize(@NonNull LineEntity lineEntity) {
                return SimpleUtil.getScaledValue(42);
            }
        });
        xAxis.setAxisValueFormat(integer -> Label.obtain((integer + 1) + "月"));
    }
    
    private void initLineChart2() {
        XAxis xAxis = mLineChart2.getXAxis();
        xAxis.setDrawGridLine(true);
        xAxis.setGridUseEndPadding(true);
        xAxis.setLabelAlign(Align.CENTER);
        xAxis.setLabelOverAlign(Align.LEFT);
        xAxis.setLabelCount(12);
        xAxis.setLabelMaxLines(2);
        xAxis.setLabelOffsetAxis(SimpleUtil.getScaledValue(10));
        xAxis.setEndPadding(SimpleUtil.getScaledValue(30));
        
        YAxis yAxis = mLineChart2.getYAxis();
        yAxis.setDrawGridLine(true);
        yAxis.setGridUseEndPadding(true);
        yAxis.setLabelAlign(Align.RIGHT);
        yAxis.setLabelMaxLines(2);
        yAxis.setLabelOffsetAxis(SimpleUtil.getScaledValue(10));
        yAxis.setEndPadding(SimpleUtil.getScaledValue(30));
        yAxis.setLabelMaxWidth(SimpleUtil.getScaledValue(100f));
        yAxis.setLabelCount(11);
        yAxis.setLabelMinWidth(SimpleUtil.getScaledValue(60));
        yAxis.setMin(0);
        yAxis.setMax(200);
        
        mLineChart2.setHighLightRender(new LineChartHighLightRender(mLineChart2, Color.GREEN, 4f));
        xAxis.setAxisValueFormat(integer -> {
            if (integer < 10) {
                return Label.obtain((integer + 1) + "月", integer % 2 == 0 ? 2 : 0);
            } else {
                return Label.obtain((integer + 1) + "月");
            }
        });
        
        mPaint.setPathEffect(new DashPathEffect(new float[]{10f, 10f}, 0));
        mPaint.setStyle(Style.STROKE);
        mPaint.setColor(0xFF106CF5);
        mPaint.setStrokeWidth(5f);
        
        mLineChart2.setCustomRender((canvas, start, top, end, bottom) -> {
            if (mLineChart2.getAnimator().getProgress() < 1f) {
                return;
            }
            
            List<? extends LineData> data = mLineChart2.getData();
            if (data == null || data.size() == 0) {
                return;
            }
            
            LineData lineData = data.get(0);
            List<LineEntity> values = lineData.getValues();
            LineEntity entity = null;
            for (LineEntity value : values) {
                if (entity == null) {
                    entity = value;
                } else if (entity.getValue() < value.getValue()) {
                    entity = value;
                }
            }
            
            if (entity == null) {
                return;
            }
            
            RectF rectF = entity.getDrawRectF();
            mPath.reset();
            mPath.moveTo(mLineChart2.getYAxis().getDrawRectF().right, rectF.top);
            mPath.lineTo(rectF.left, rectF.top);
            canvas.drawPath(mPath, mPaint);
            
            mPath.reset();
            mPath.moveTo(rectF.left, mLineChart2.getXAxis().getDrawRectF().top);
            mPath.lineTo(rectF.left, rectF.top);
            canvas.drawPath(mPath, mPaint);
        });
    }
    
    /**
     * 设置图表数据
     */
    private void fillLineChart1Data() {
        List<LineData> data = new ArrayList<>();
        XAxis xAxis = mLineChart.getXAxis();
        YAxis yAxis = mLineChart.getYAxis();
        
        List<LineEntity> entityList = new ArrayList<>();
        int count = xAxis.getLabelCount();
        float avg = 0f;
        LineEntity max = null;
        for (int i = 0; i < count; i++) {
            LineEntity entity =
                new LineEntity(i, (float) (yAxis.getMin() + Math.random() * (yAxis.getMax() - yAxis.getMin())));
            avg += entity.getValue();
            if (i == 0) {
                entity.setLabelGravity(Gravity.START);
            } else if (i == count - 1) {
                entity.setLabelGravity(Gravity.END);
            } else {
                entity.setLabelGravity(Gravity.CENTER);
            }
            
            entity.setLabelOffset(10);
            entity.setIndicatorDrawable(ContextCompat.getDrawable(this, R.drawable.bg_circle_blue));
            entity.setDrawLabel(false);
            entity.setDrawIndicator(true);
            entity.setLabel(((int) entity.getValue()) + "%");
            entityList.add(entity);
            
            if (max == null || max.getValue() < entity.getValue()) {
                max = entity;
            }
        }
        
        if (max != null) {
            max.setDrawLabel(true);
        }
        
        LineData lineData = new LineData(entityList);
        lineData.setLineWidth(SimpleUtil.getScaledValue(4));
        lineData.setLineStyle(LineData.LINER);
        lineData.setFillBg(true);
        lineData.setFillBgDrawable(ContextCompat.getDrawable(this, R.drawable.bg_line_chart_fill_bg));
        lineData.setLineColor(0xFF106CF5);
        lineData.setLineShaderFactory((left, top, right, bottom) -> {
            if (mGradient == null) {
                mGradient = new LinearGradient(left, 0,
                    right, 0, new int[]{Color.YELLOW, Color.RED, Color.GREEN}, null, Shader.TileMode.CLAMP);
            }
            return mGradient;
        });
        
        List<AddedLine> addedLines = new ArrayList<>();
        AddedLine addedLine = new AddedLine(avg / entityList.size());
        addedLine.setPathEffect(new DashPathEffect(new float[]{10f, 10f}, 0));
        addedLine.setLabel("测试数据");
        addedLine.setLineWidth(SimpleUtil.getScaledValue(2));
        addedLine.setLineColor(0xff5283C9);
        addedLines.add(addedLine);
        lineData.setAddedLines(addedLines);
        data.add(lineData);
        
        mLineChart.setData(data);
        mLineChart.animDraw(2000);
    }
    
    /**
     * 设置图表数据
     */
    private void fillLineChart2Data() {
        List<LineData> data = new ArrayList<>();
        XAxis xAxis = mLineChart2.getXAxis();
        YAxis yAxis = mLineChart2.getYAxis();
        
        for (int j = 0; j < 2; j++) {
            List<LineEntity> entityList = new ArrayList<>();
            int count = xAxis.getLabelCount();
            float avg = 0f;
            LineEntity max = null;
            for (int i = 0; i < count; i++) {
                LineEntity entity =
                    new LineEntity(i, (float) (yAxis.getMin() + Math.random() * (yAxis.getMax() - yAxis.getMin())));
                avg += entity.getValue();
                if (i == 2) {
                    entity.setLineStyle(LineStyle.DOTTED_LINE);
                } else if (i == 4) {
                    entity.setLineStyle(LineStyle.DOTTED_LINE);
                }
                
                if (i == 0) {
                    entity.setLabelGravity(Gravity.START);
                } else if (i == count - 1) {
                    entity.setLabelGravity(Gravity.END);
                } else {
                    entity.setLabelGravity(Gravity.CENTER);
                }
                
                entity.setLabelOffset(10);
                if (j == 0) {
                    entity.setIndicatorDrawable(ContextCompat.getDrawable(this, R.drawable.bg_circle_blue));
                } else {
                    if (i == 7) {
                        entity.setDraw(false);
                    }
                    entity.setIndicatorDrawable(ContextCompat.getDrawable(this, R.drawable.bg_circle_red));
                }
                entity.setDrawLabel(false);
                entity.setDrawIndicator(true);
                entity.setLabel(((int) entity.getValue()) + "%");
                entityList.add(entity);
                
                if (max == null || max.getValue() < entity.getValue()) {
                    max = entity;
                }
            }
            
            if (max != null) {
                max.setDrawLabel(true);
            }
            
            LineData lineData = new LineData(entityList);
            lineData.setLineWidth(SimpleUtil.getScaledValue(2));
            lineData.setLineStyle(j == 0 ? LineData.HORIZONTAL_BEZIER : LineData.LINER);
            lineData.setFillBg(true);
            if (j == 0) {
                lineData.setFillBgColor(0x335283C9);
            } else {
                lineData.setFillBgColor(0x33BE3E38);
            }
            
            lineData.setLineColor(j == 0 ? 0xFF106CF5 : Color.RED);
            
            List<AddedLine> addedLines = new ArrayList<>();
            AddedLine addedLine = new AddedLine(avg / entityList.size());
            addedLine.setLabel("测试数据" + j);
            addedLine.setLineWidth(SimpleUtil.getScaledValue(2));
            addedLine.setLineColor(j == 0 ? 0xff5283C9 : Color.RED);
            addedLines.add(addedLine);
            lineData.setAddedLines(addedLines);
            data.add(lineData);
        }
        
        //noinspection ConstantConditions
        AddedLine addedLine = data.get(0).getAddedLines().get(0);
        //noinspection ConstantConditions
        AddedLine addedLine1 = data.get(1).getAddedLines().get(0);
        if (addedLine.getValue() >= addedLine1.getValue()) {
            addedLine.setLabelGravity(android.view.Gravity.TOP | android.view.Gravity.END);
            addedLine1.setLabelGravity(android.view.Gravity.BOTTOM | android.view.Gravity.END);
        } else {
            addedLine.setLabelGravity(android.view.Gravity.BOTTOM | android.view.Gravity.END);
            addedLine1.setLabelGravity(android.view.Gravity.TOP | android.view.Gravity.END);
        }
        
        mLineChart2.setData(data);
        mLineChart2.animDraw(2000);
    }
}
